<template>
  <div class="pie-chart-container">
    <!-- 饼图容器，需要指定 ID 供 VChart 使用 -->
    <div id="pie-chart" class="chart-wrapper"></div>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted, ref } from 'vue';
import VChart from '@visactor/vchart'; // 导入 VChart 库

// 图表配置项
const spec = {
  type: 'pie',
  data: [
    {
      id: 'id0',
      values: [
        { type: '大专', value: '200' },
        { type: '本科', value: '400' },
        { type: '硕士', value: '200' },
        { type: '博士', value: '200' },
        { type: '高中及以下', value: '200' },

      ]
    }
  ],
  outerRadius: 0.8,
  innerRadius: 0.5,
  padAngle: 0.6,
  valueField: 'value',
  categoryField: 'type',
  pie: {
    style: {
      cornerRadius: 10
    },
    state: {
      hover: {
        outerRadius: 0.85,
        stroke: '#000',
        lineWidth: 1
      },
      selected: {
        outerRadius: 0.85,
        stroke: '#000',
        lineWidth: 1
      }
    }
  },
  title: {
    visible: true,
    text: '学历占比'
  },
  legends: {
    visible: true,
    orient: 'right'
  },
  label: {
    visible: true
  },
  tooltip: {
    mark: {
      content: [
        {
          key: datum => datum['type'],
          value: datum => datum['value'] + '%'
        }
      ]
    }
  }
};

// 存储图表实例
const vchart = ref(null);

// 在组件挂载后初始化图表
onMounted(() => {
  // 创建图表实例，绑定到指定 DOM 元素
  vchart.value = new VChart(spec, { dom: 'pie-chart' });
  // 渲染图表
  vchart.value.renderSync();
});

// 组件卸载时销毁图表，避免内存泄漏
onUnmounted(() => {
  if (vchart.value && typeof vchart.value.destroy === 'function') {
    vchart.value.destroy();
  }
});

const handleResize = () => {
  // 窗口变化时，触发图表重绘
  if (vchartInstance) {
    vchartInstance.resize();
  }
};
</script>

<style scoped>
.pie-chart-container {
  width: 100%;
  height: 100%;
}

.chart-wrapper {
  width: 100%;
  height: 100%;
  min-height: 400px; /* 确保图表有足够的显示空间 */
}
</style>
